<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { SystemOAuth2ClientApi } from '#/api/system/oauth2/client';

import { confirm, Page, useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteOAuth2Client,
  getOAuth2ClientPage,
  refreshSecret,
  refreshSm2,
} from '#/api/system/oauth2/client';
import { Image } from '#/components/image';
import { $t } from '#/locales';

import { useGridColumns, useGridFormSchema } from './data';
import Detail from './modules/detail.vue';
import Form from './modules/form.vue';

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

const [DetailModal, detailModalApi] = useVbenModal({
  connectedComponent: Detail,
  destroyOnClose: true,
});

/** 刷新表格 */
function handleRefresh() {
  gridApi.reload();
}

/** 创建 OAuth2 客户端 */
function handleCreate() {
  formModalApi.setData(null).open();
}

/** 编辑 OAuth2 客户端 */
function handleEdit(row: SystemOAuth2ClientApi.OAuth2Client) {
  formModalApi.setData(row).open();
}

/** 查看 OAuth2 客户端  */
function handleDetail(row: SystemOAuth2ClientApi.OAuth2Client) {
  detailModalApi.setData(row).open();
}

/** 删除 OAuth2 客户端 */
async function handleDelete(row: SystemOAuth2ClientApi.OAuth2Client) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.name]),
    duration: 0,
  });
  try {
    await deleteOAuth2Client(row.id!);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.name]),
    });
    handleRefresh();
  } finally {
    hideLoading();
  }
}
async function handleRefreshSecret(row: SystemOAuth2ClientApi.OAuth2Client) {
  // 弹出model确认框
  confirm(`是否确认刷新“${row.name}”秘钥`)
    .then(async () => {
      const hideLoading = message.loading({
        content: '秘钥刷新中',
        duration: 0,
      });
      try {
        await refreshSecret(row.id!);
        message.success({
          content: '刷新成功',
        });
        handleRefresh();
      } finally {
        hideLoading();
      }
    })
    .catch(() => {});
}
async function handleRefreshSm2(row: SystemOAuth2ClientApi.OAuth2Client) {
  confirm(`是否确认刷新“${row.name}”SM2加解密秘钥`)
    .then(async () => {
      const hideLoading = message.loading({
        content: 'SM2加解密秘钥刷新中',
        duration: 0,
      });
      try {
        await refreshSm2(row.id!);
        message.success({
          content: '刷新成功',
        });
        handleRefresh();
      } finally {
        hideLoading();
      }
    })
    .catch(() => {});
}
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    columns: useGridColumns(),
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getOAuth2ClientPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<SystemOAuth2ClientApi.OAuth2Client>,
});
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="handleRefresh" />
    <DetailModal @success="handleRefresh" />
    <Grid table-title="OAuth2 客户端列表">
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: $t('ui.actionTitle.create', [' OAuth2.0 客户端']),
              type: 'primary',
              icon: ACTION_ICON.ADD,
              auth: ['system:oauth2-client:create'],
              onClick: handleCreate,
            },
          ]"
        />
      </template>
      <template #logo="{ row }">
        <Image :src="row.logo" />
      </template>
      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: '查看',
              type: 'link',
              icon: ACTION_ICON.VIEW,
              auth: ['system:oauth2-client:query'],
              onClick: handleDetail.bind(null, row),
            },
            {
              label: $t('common.edit'),
              type: 'link',
              icon: ACTION_ICON.EDIT,
              auth: ['system:oauth2-client:update'],
              onClick: handleEdit.bind(null, row),
            },
          ]"
          :drop-down-actions="[
            {
              label: $t('common.delete'),
              type: 'link',
              danger: true,
              auth: ['system:oauth2-client:delete'],
              popConfirm: {
                title: $t('ui.actionMessage.deleteConfirm', [row.name]),
                confirm: handleDelete.bind(null, row),
              },
            },
            {
              label: '刷新秘钥',
              type: 'link',
              auth: ['system:oauth2-client:refresh'],
              onClick: handleRefreshSecret.bind(null, row),
            },
            {
              label: '刷新加解密秘钥',
              type: 'link',
              auth: ['system:oauth2-client:refresh'],
              onClick: handleRefreshSm2.bind(null, row),
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
